package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.pojo.User;
import com.qf.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {


    @Override
    public  long selectCountByUserName(String username) {
        QueryRunner qf = new QueryRunner(DataSourceUtils.getDataSource());
        String sql ="select count(0) from tb_user where username = ?";
        try {
            Long count = (Long) qf.query(sql, new ScalarHandler(), username);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("检测用户名是否存在失败");
        }
        return 0;
    }

    @Override
    public int insert(User user) {
        QueryRunner qf = new QueryRunner(DataSourceUtils.getDataSource());
        String sql ="insert into tb_user values(null ,?,md5(?) ,?,?,?,?,?)";
        try {
            int count = qf.update(sql,user.getUsername(),user.getPassword(),user.getEmail(),user.getGender(),user.getFlag(),1,"");

            return count;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("注册用户失败");
        }
        return 0;
    }

    @Override
    public User selectByUserNameAndPassword(String username, String password) {
        QueryRunner qf = new QueryRunner(DataSourceUtils.getDataSource());
        String sql ="select id,username,password,email,gender,flag,role,code from tb_user where username =? and password=md5(?)";
        try {
            User user = qf.query(sql, new BeanHandler<>(User.class), username,password);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("检测用户名是否存在失败");
        }
        return null;
    }
}
